<template>
  <div class="d1-graphic-chart-question">
    <div class="question-container">
      <!-- 左侧富文本区域 -->
      <MaterialORnot />

      <!-- 右侧题目区域 -->

      <div class="right-list">
        <!-- <askStatus :is-analysis="true" :is-correct="correct" /> -->

        <div
          class="right-content"
          :class="{ 'full-width': !examStore.currQuestion.materials }"
        >
          <!-- 没有表格数据正常渲染 -->
          <!-- <div
            v-if="!tableOfTitle"
            class="question-title"
            v-html="mathHTMLToShow(examStore.currQuestion.title)"
          ></div> -->

          <!-- 表格渲染 -->
          <div class="question-title">
            <template v-for="item in tableOfTitle">
              <el-table
                v-if="item == '<p>{【表格插入位置标识】}</p>'"
                ref="excelRef"
                style="width: 100%"
                :data="table?.[0]?.data?.slice(1)"
                border
              >
                <el-table-column
                  :label="table?.[0]?.data?.[0]?.[it]"
                  :prop="it"
                  v-for="(it, ind) in table?.[0]?.filed"
                  sortable
                />
                <template #empty>
                  <div class="custom-loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    正在加载中...
                  </div>
                </template>
              </el-table>

              <span
                v-else
                v-html="mathHTMLToShow(item)"
                @change="handleSelectChange"
              ></span>
            </template>
          </div>

          <!-- <div
          v-for="(group, index) in props.questionGroups"
          :key="index"
          class="question-group"
        >
          <div class="question-row">
            <div class="question-content" v-html="group.content"></div>
            <div class="operation-area">
              <div class="answer-area">
                <el-select
                  v-model="userAnswers[index]"
                  placeholder="请选择"
                  class="answer-select"
                >
                  <el-option
                    v-for="option in group.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
        </div> -->

          <!-- <div v-if="props.isAnalysis" class="analysis-area">
          <div class="answer-item">
            <span>答案：</span>
            <span class="answer-value">{{ userAnswers[index] }}</span>
            <el-icon v-if="userAnswers[index] === correctAnswers[index]" color="#67C23A">
              <Select />
            </el-icon>
            <el-icon v-else color="#F56C6C">
              <Close />
            </el-icon>
          </div>
        </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import askStatus from "./askStatus.vue";
import { Loading } from "@element-plus/icons-vue";
import MaterialORnot from "./materialORnot.vue";
import { ref, watch, onMounted, onUpdated } from "vue";
import { getQuestionExcel } from "@/service/exam";
import { Select, Close } from "@element-plus/icons-vue";
import { mathHTMLToShow, sortTable } from "@/utils/index";
import { useExam } from "@/stores/exam.js";
const examStore = useExam();

// 下拉选择每项值的记录
let child = examStore.currQuestion.childList.map((it, ind) => {
  return {
    questionid3: it.id,
    answer: 0,
    is_right: 0,
  };
});

// 下拉选择框的选项
const options = computed(() => {
  return examStore.currQuestion?.childList.map((it) => {
    return {
      option: it?.answerList.map((i) => ({
        value: i.id,
        label: i.value,
        selected: i.is_check == 1 ? true : false,
      })),
    };
  });
});

// 1. 按表格标识拆分字符串
const splitByTableMarker = (text) => {
  const tableMarker = "<p>{【表格插入位置标识】}</p>";
  const parts = text.split(new RegExp(`(${escapeRegExp(tableMarker)})`));
  return parts.filter((part) => part.trim() !== "");
};

// 2. 替换下拉选项标识为原生select
const replaceDropdownMarker = (html) => {
  let count = 0;
  return html.replace(/{【下拉选项标识】}/g, () => {
    const dropdownHtml = `
    <select ${
      examStore.currQuestion.showAnswer && "disabled"
    } class="native-select native-select-${count}${
      examStore.currQuestion.showAnswer && examStore.currQuestion.child[count]?.is_right
        ? " correct"
        : ""
    }${
      examStore.currQuestion.showAnswer && !examStore.currQuestion.child[count]?.is_right
        ? " wrong"
        : ""
    }">
      <option value="">请选择</option>
      ${options.value[count].option
        .map((i) => {
          return `<option value="${i.value}" ${i.selected ? "selected" : ""}> ${
            i.label
          } </option>`;
        })
        .join()}
    </select>
  `;
    count++;
    return dropdownHtml;
  });
};

// 辅助函数：转义正则特殊字符
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// 表格数据拆分
const table = ref([]);
const tableLoading = ref(true);
const tableOfTitle = computed(() => {
  return splitByTableMarker(examStore.currQuestion.title).map((part) => {
    return replaceDropdownMarker(part);
  });
});

console.log(tableOfTitle, "tableOfTitle");

// 事件委托， 下拉框选择值赋值
const handleSelectChange = (event) => {
  if (examStore.currQuestion.showAnswer) {
    console.log(event, "sssssssss");
    event.target.disabled = true;
    return;
  }

  if (event.target.classList[0].includes("native-select")) {
    const value = event.target.value;
    console.log("选中值：", value);

    // 取出下标值
    let index = parseInt(
      event.target.classList[1].charAt(event.target.classList[1].length - 1)
    );
    console.log("选中值index：", index);

    options.value[index].option.forEach((i) => {
      if (i.value == value) {
        i.selected = true;
      } else {
        i.selected = false;
      }
    });

    // 每项正确值记录
    child.forEach((it, ind) => {
      if (ind == index) {
        it.answer =
          examStore.currQuestion.childList[index].answerList.find((i) => i.id == value)
            .id || "";
        it.is_right =
          examStore.currQuestion.childList[index].answerList.find((i) => i.id == value)
            .key || 0;
      }
    });

    examStore.currQuestion.child = child.filter((i) => i.answer);
    examStore.currQuestion.is_right = examStore.examInfo.section[
      examStore.currQuestion.sectionIndex
    ].question[examStore.currQuestion.index].is_right = child.every(
      (i) => i.is_right == 1
    )
      ? 1
      : 0;
  }
};

// 获取表格数据
const getQuestionExcelFn = async () => {
  const data = { qid: examStore.currQuestion.id, tid: 0 };
  const res = await getQuestionExcel(data);
  if (res.code === "000000") {
    tableLoading.value = false;
    table.value = [
      {
        name: "表格",
        data: sortTable(processTable(res.data)),
        filed: Object.keys(sortTable(res.data)[0] || {}).filter((it) =>
          it.includes("field")
        ),
      },
    ];
  }
};

// console.log(tableOfTitle.value, "tableOfTitletableOfTitle");
// if (examStore.currQuestion.title.includes("<p>{【表格插入位置标识】}</p>"))

watch(
  () => examStore.currQuestion.childList,
  (val) => {
    val.forEach((it, ind) => {
      child[ind].answer = it.answerList.find((i) => i.is_check)?.id || 0;
      child[ind].is_right = it.answerList.find((i) => i.is_check)?.key || 0;
    });

    examStore.currQuestion.child = child.filter((i) => i.answer);
    examStore.currQuestion.is_right = examStore.examInfo.section[
      examStore.currQuestion.sectionIndex
    ].question[examStore.currQuestion.index].is_right = child.every(
      (i) => i.is_right == 1
    )
      ? 1
      : 0;
  },
  {
    deep: true,
    immediate: true,
  }
);

// 监听题目切换，做表格数据切换请求
watch(
  () => examStore.currQuestion?.id,
  () => {
    table.value = [];
    if (examStore.currQuestion.title.includes("<p>{【表格插入位置标识】}</p>")) {
      getQuestionExcelFn();
    }
  },
  {
    immediate: true,
  }
);

const props = defineProps({
  leftContent: {
    type: String,
    default: "",
  },
  questionGroups: {
    type: Array,
    required: true,
  },
  isAnalysis: {
    type: Boolean,
    default: false,
  },
  correctAnswers: {
    type: Array,
    default: () => [],
  },
});

const userAnswers = ref([]);

const emit = defineEmits(["update:answers"]);
watch(
  userAnswers,
  (newVal) => {
    emit("update:answers", newVal);
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
/* 针对包含文本和下拉框的容器 */
.question-title {
  white-space: nomal; /* 禁止换行 */

  :deep() {
    .native-select {
      /* 基本尺寸和间距 */
      padding: 4px 12px;
      margin: 0px 4px;
      // width: 200px;

      /* 边框和圆角 */
      border: 1px solid #ccc;
      border-radius: 4px;

      /* 背景和文字 */
      background-color: #fff;
      color: #333;
      font-size: 14px;

      /* 移除默认外观 */
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;

      /* 添加自定义下拉箭头 */
      background-image: url("../../static/down.png");
      background-repeat: no-repeat;
      background-position: right 10px center;
      background-size: 16px;
      padding-right: 30px;

      &.wrong {
        border: 1px solid #e52121;
        color: #e52121;

        &:hover {
          border-color: #e52121;
        }
      }

      &.correct {
        border: 1px solid #1e8fda;
        color: #1e8fda;
        &:hover {
          border-color: #1e8fda;
        }
      }
    }

    /* 悬停状态 */
    .native-select:hover {
      border-color: #888;
    }

    /* 聚焦状态 */
    .native-select:focus {
      outline: none;
      border-color: #4285f4;
      box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
    }

    /* 禁用状态 */
    .native-select:disabled {
      background-color: #f5f5f5;
      color: #999;
      cursor: not-allowed;
    }
  }
}

.answer-select {
  width: 120px;
}

.right-list {
  display: flex;
  flex: 1;
}

.d1-graphic-chart-question {
  .question-container {
    display: flex;
    gap: 20px;

    .left-content {
      flex: 0 0 45%;

      .content-box {
        border-right: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 20px;
        height: 100%;
      }
    }

    .right-content {
      flex: 0 0 55%;

      &.full-width {
        flex: 1;
      }
    }
  }

  .question-group {
    margin-bottom: 20px;
  }

  .question-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    line-height: 1.5;

    .question-content {
      :deep(p) {
        display: inline;
        margin: 0;
      }
    }

    .operation-area {
      white-space: nowrap;

      .answer-select {
        width: 120px;
      }
    }
  }

  .analysis-area {
    .answer-item {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-top: 15px;
    }
  }
}
</style>
